import axios from 'axios'
import { config, API_BASE_URL, AI_BASE_URL } from './config'
import { PasswordCrypto, FrontendCrypto } from './crypto'

// API基础配置 - 双后端架构
const API_BASE_URL_FINAL = API_BASE_URL
const AI_API_BASE_URL_FINAL = AI_BASE_URL

// 创建主服务axios实例 (Node.js)
const apiClient = axios.create({
  baseURL: API_BASE_URL_FINAL,
  timeout: config.api.timeout,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 创建AI服务axios实例 (Python FastAPI)
const aiApiClient = axios.create({
  baseURL: AI_API_BASE_URL_FINAL,
  timeout: 900000, // AI处理需要更长时间 (15分钟)
  headers: {
    'Content-Type': 'application/json',
  },
})

// 创建长时间任务的axios实例 (用于AI分割等耗时操作)
const longTaskApiClient = axios.create({
  baseURL: AI_API_BASE_URL_FINAL,
  timeout: 0, // 无超时限制，适用于复杂AI任务
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器 - 添加认证token
const addAuthInterceptor = (client: typeof axios) => {
  client.interceptors.request.use(
    (config) => {
      const token = localStorage.getItem('auth_token')
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )
}

// 响应拦截器 - 处理错误
const addResponseInterceptor = (client: typeof axios) => {
  client.interceptors.response.use(
    (response) => response,
    (error) => {
      if (error.response?.status === 401) {
        // token过期，跳转到登录页
        localStorage.removeItem('auth_token')
        window.location.href = '/login'
      }
      
      // 增强错误处理
      if (error.code === 'ECONNREFUSED') {
        console.error('服务器连接失败，请检查服务是否启动')
        error.userMessage = '无法连接到服务器，请检查服务是否正常运行'
      } else if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) {
        console.error('请求超时，可能是AI处理时间较长')
        error.userMessage = 'AI处理时间较长，请耐心等待或稍后重试'
      } else if (error.response?.status >= 500) {
        console.error('服务器内部错误:', error.response?.data)
        error.userMessage = '服务器处理出错，请稍后重试'
      } else if (error.response?.status === 429) {
        console.error('请求过于频繁')
        error.userMessage = '请求过于频繁，请稍后再试'
      }
      
      return Promise.reject(error)
    }
  )
}

// 应用拦截器
addAuthInterceptor(apiClient)
addAuthInterceptor(aiApiClient)
addAuthInterceptor(longTaskApiClient)
addResponseInterceptor(apiClient)
addResponseInterceptor(aiApiClient)
addResponseInterceptor(longTaskApiClient)

// 类型定义
export interface User {
  username: string
  role: string
  permissions: string[]
}

export interface LoginRequest {
  username: string
  password: string
}

export interface SecureLoginRequest {
  username: string
  password: string
  encrypted?: boolean
  timestamp?: number
  signature?: string
}

export interface LoginResponse {
  access_token: string
  token_type: string
  user_info: User
}

export interface TaskStatus {
  task_id: string
  status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'
  progress: number
  result?: any
  error?: string
  created_at: number
  started_at?: number
  completed_at?: number
  eta?: number
}

export interface QueueStats {
  total_tasks: number
  completed_tasks: number
  failed_tasks: number
  pending_tasks: number
  running_tasks: number
  cache_hits: number
  cache_size: number
  cache_hit_rate: number
  average_processing_time: number
}

// 预约相关类型定义
export interface Hospital {
  id: string
  name: string
  address: string
  phone: string
  level: string
  city: string
  distance?: number
}

export interface Department {
  id: string
  hospitalId: string
  name: string
  description: string
  doctorCount: number
  availableSlots: number
}

export interface Doctor {
  id: string
  departmentId: string
  name: string
  title: string
  specialty: string
  experience: string
  avatar: string
  rating: number
  price: number
}

export interface TimeSlot {
  time: string
  available: boolean
  price: number
  reason?: string
}

export interface PatientInfo {
  name: string
  phone: string
  idCard?: string
}

export interface AppointmentOrder {
  id: string
  userId: string
  hospitalId: string
  hospitalName: string
  departmentId: string
  departmentName: string
  doctorId: string
  doctorName: string
  appointmentDate: string
  timeSlot: string
  status: 'pending' | 'confirmed' | 'completed' | 'cancelled'
  price: number
  queueNumber?: number
  createTime: string
  remark?: string // 管理员备注
  patientInfo?: PatientInfo
}

export interface CreateAppointmentRequest {
  hospitalId: string
  hospitalName: string
  departmentId: string
  departmentName: string
  doctorId: string
  doctorName: string
  appointmentDate: string
  timeSlot: string
  price: number
  patientInfo?: PatientInfo
}

export interface AppointmentListResponse {
  success: boolean
  data: {
    appointments: AppointmentOrder[]
    total: number
    page: number
    limit: number
  }
  message?: string
}

export interface HospitalListResponse {
  success: boolean
  data: {
    hospitals: Hospital[]
    total: number
    page: number
    limit: number
  }
  message?: string
}

export interface FloorPlan {
  fileId: string
  status: string
  originalFilename: string
  fileUrl: string
  uploadedAt: string
}

export interface SegmentResult {
  maskUrl: string
  rooms: Array<{
    id: string
    type: string
    polygon: number[][]
    label: string
    area: number
    confidence: number
  }>
  doors: Array<{
    id: string
    type: string
    coordinates: number[]
    confidence: number
  }>
  windows: Array<{
    id: string
    type: string
    coordinates: number[]
    confidence: number
  }>
  texts: Array<{
    id: string
    bbox: number[]
    text: string
    confidence: number
  }>
  metadata: any
}

// API方法
export const api = {
  // 基础HTTP方法
  get: (url: string, config?: any) => apiClient.get(url, config).then(res => res.data),
  post: (url: string, data?: any, config?: any) => apiClient.post(url, data, config).then(res => res.data),
  put: (url: string, data?: any, config?: any) => apiClient.put(url, data, config).then(res => res.data),
  delete: (url: string, config?: any) => apiClient.delete(url, config).then(res => res.data),
  patch: (url: string, data?: any, config?: any) => apiClient.patch(url, data, config).then(res => res.data),

  // 认证相关
  auth: {
    login: (credentials: LoginRequest): Promise<LoginResponse> =>
      apiClient.post('/auth/login', credentials).then(res => res.data),
    
    // 安全登录（带密码加密）
    secureLogin: async (credentials: LoginRequest): Promise<LoginResponse> => {
      const timestamp = Date.now()
      const encodedPassword = FrontendCrypto.encodePassword(credentials.password)
      
      const secureCredentials: SecureLoginRequest = {
        username: credentials.username,
        password: encodedPassword,
        encrypted: true,
        timestamp,
        signature: FrontendCrypto.generateSignature(
          { username: credentials.username, timestamp }, 
          timestamp
        )
      }
      
      return apiClient.post('/auth/secure-login', secureCredentials).then(res => res.data)
    },
    
    getCurrentUser: (): Promise<User> =>
      apiClient.get('/auth/me').then(res => res.data),
    
    logout: (): Promise<void> =>
      apiClient.post('/auth/logout').then(() => {
        localStorage.removeItem('auth_token')
      }),
    
    // 修改密码
    changePassword: async (oldPassword: string, newPassword: string): Promise<void> => {
      const timestamp = Date.now()
      const encodedOldPassword = FrontendCrypto.encodePassword(oldPassword)
      const encodedNewPassword = FrontendCrypto.encodePassword(newPassword)
      
      const data = {
        oldPassword: encodedOldPassword,
        newPassword: encodedNewPassword,
        encrypted: true,
        timestamp,
        signature: FrontendCrypto.generateSignature({ timestamp }, timestamp)
      }
      
      return apiClient.post('/auth/change-password', data).then(() => {})
    },
  },

  // 系统信息
  system: {
    getHealth: () =>
      aiApiClient.get('/health').then(res => res.data),
    
    getStats: () =>
      aiApiClient.get('/system/stats').then(res => res.data),
  },

  // 平面图处理
  floor: {
    upload: (file: File): Promise<FloorPlan> => {
      const formData = new FormData()
      formData.append('file', file)
      return aiApiClient.post('/ai/floor/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then(res => res.data)
    },

    segment: (fileId: string): Promise<SegmentResult | { task_id: string, status: string }> =>
      longTaskApiClient.post('/ai/floor/segment', { fileId }).then(res => res.data),

    vectorize: (segData: any, fileId: string): Promise<any> =>
      longTaskApiClient.post('/ai/floor/vectorize', { seg: segData, fileId }).then(res => res.data),

    getStatus: (fileId: string): Promise<any> =>
      aiApiClient.get(`/ai/floor/status/${fileId}`).then(res => res.data),

    list: (): Promise<FloorPlan[]> =>
      aiApiClient.get('/ai/floor/list').then(res => res.data),
  },

  // 3D重建
  reconstruction: {
    reconstruct: (vectorId: string, assetsPreset: string = 'hospital_basic'): Promise<any> =>
      longTaskApiClient.post('/ai/3d/reconstruct', { vectorId, assetsPreset }).then(res => res.data),

    getStatus: (vectorId: string): Promise<any> =>
      aiApiClient.get(`/ai/3d/status/${vectorId}`).then(res => res.data),

    getAssetPresets: (): Promise<any> =>
      aiApiClient.get('/ai/3d/assets/presets').then(res => res.data),
  },

  // 任务管理 - 使用AI服务
  tasks: {
    getQueueStats: (): Promise<QueueStats> =>
      aiApiClient.get('/tasks/queue/stats').then(res => res.data),

    getTaskStatus: (taskId: string): Promise<TaskStatus> =>
      aiApiClient.get(`/tasks/status/${taskId}`).then(res => res.data),

    getBatchStatus: (taskIds: string[]): Promise<any> =>
      aiApiClient.get(`/tasks/batch/status?task_ids=${taskIds.join(',')}`).then(res => res.data),

    cancelTask: (taskIds: string[]): Promise<any> =>
      aiApiClient.post('/tasks/cancel', { task_ids: taskIds }).then(res => res.data),

    batchSegment: (fileIds: string[], priority: string = 'normal'): Promise<any> =>
      aiApiClient.post('/tasks/batch/segment', { file_ids: fileIds, priority }).then(res => res.data),

    clearCache: (pattern?: string): Promise<any> =>
      aiApiClient.post('/tasks/cache/clear', pattern ? { pattern } : {}).then(res => res.data),

    getHistory: (limit: number = 50, offset: number = 0, statusFilter?: string): Promise<any> =>
      aiApiClient.get('/tasks/history', { 
        params: { limit, offset, status_filter: statusFilter }
      }).then(res => res.data),

    getPerformanceMetrics: (): Promise<any> =>
      aiApiClient.get('/tasks/performance/metrics').then(res => res.data),
  },

  // 仿真相关 - 使用AI服务
  simulation: {
    start: (params: any): Promise<any> =>
      aiApiClient.post('/simulate/start', params).then(res => res.data),

    getStatus: (runId: string): Promise<any> =>
      aiApiClient.get(`/simulate/status/${runId}`).then(res => res.data),

    getSummary: (runId: string): Promise<any> =>
      aiApiClient.get(`/simulate/summary/${runId}`).then(res => res.data),

    getScenarios: (): Promise<any> =>
      aiApiClient.get('/simulate/scenarios').then(res => res.data),

    delete: (runId: string): Promise<any> =>
      aiApiClient.delete(`/simulate/${runId}`).then(res => res.data),
  },

  // 统一智能建模相关
unifiedModeling: {
  analyze: (fileId: string): Promise<any> =>
    aiApiClient.post('/ai/intelligent/analyze', { file_id: fileId }).then(res => res.data),

  getAnalysisStatus: (taskId: string): Promise<any> =>
    aiApiClient.get(`/ai/intelligent/analysis/${taskId}`).then(res => res.data),

  build: (params: any): Promise<any> =>
    longTaskApiClient.post('/ai/intelligent/build', params).then(res => res.data),

  getStatus: (modelId: string): Promise<any> =>
    aiApiClient.get(`/ai/intelligent/status/${modelId}`).then(res => res.data),

  getStrategies: (): Promise<any> =>
    aiApiClient.get('/ai/intelligent/strategies').then(res => res.data),

  download: (fileType: string, taskId: string): Promise<Blob> =>
    aiApiClient.get(`/ai/intelligent/download/${fileType}/${taskId}`, { 
      responseType: 'blob' 
    }).then(res => res.data),
},

// 保持向后兼容
intelligentModeling: {
  analyze: (fileId: string): Promise<any> =>
    aiApiClient.post('/ai/intelligent/analyze', { file_id: fileId }).then(res => res.data),

  build: (params: any): Promise<any> =>
    longTaskApiClient.post('/ai/intelligent/build', params).then(res => res.data),

  getStatus: (modelId: string): Promise<any> =>
    aiApiClient.get(`/ai/intelligent/status/${modelId}`).then(res => res.data),

  getStrategies: (): Promise<any> =>
    aiApiClient.get('/ai/intelligent/strategies').then(res => res.data),
},

// 地图管理API
map: {
  listSites: (q?: string, offset: number = 0, limit: number = 20): Promise<{ items: Array<{id:string,name:string,center:[number,number],zoom:number}>, total:number, offset:number, limit:number }> =>
    apiClient.get('/map/sites', { params: { q, offset, limit } }).then(res => res.data),
    
  getLevels: (siteId: string): Promise<{ site: string, levels: string[] }> =>
    apiClient.get('/map/levels', { params: { site: siteId } }).then(res => res.data),
    
  getPOIs: (siteId?: string, level?: string): Promise<{ items: any[] }> =>
    apiClient.get('/map/pois', { params: { site: siteId, level } }).then(res => res.data),
    
  getLegend: (): Promise<{ legend: any }> =>
    apiClient.get('/map/legend').then(res => res.data),
},

// 预约挂号API
appointment: {
  // 获取医院列表
  getHospitals: (params?: { city?: string; page?: number; limit?: number; q?: string }): Promise<HospitalListResponse> =>
    apiClient.get('/appointment/hospitals', { params }).then(res => res.data),

  // 获取科室列表
  getDepartments: (params?: { hospitalId?: string; page?: number; limit?: number }): Promise<any> =>
    apiClient.get('/appointment/departments', { params }).then(res => res.data),

  // 获取医生列表
  getDoctors: (params?: { hospitalId?: string; departmentId?: string; page?: number; limit?: number }): Promise<any> =>
    apiClient.get('/appointment/doctors', { params }).then(res => res.data),

  // 获取可预约时间段
  getTimeSlots: (params: { doctorId: string; date: string }): Promise<{ success: boolean; data: TimeSlot[] }> =>
    apiClient.get('/appointment/slots', { params }).then(res => res.data),

  // 创建预约订单
  createAppointment: (data: CreateAppointmentRequest): Promise<{ success: boolean; data: { orderId: string; appointment: AppointmentOrder }; message: string }> =>
    apiClient.post('/appointment/orders', data).then(res => res.data),

  // 获取我的预约列表
  getMyAppointments: (params?: { status?: string; page?: number; limit?: number }): Promise<AppointmentListResponse> =>
    apiClient.get('/appointment/orders', { params }).then(res => res.data),

  // 取消预约
  cancelAppointment: (appointmentId: string): Promise<{ success: boolean; message: string }> =>
    apiClient.delete(`/appointment/orders/${appointmentId}`).then(res => res.data),

  // 获取今日预约
  getTodayAppointment: (): Promise<{ success: boolean; data: AppointmentOrder | null }> =>
    apiClient.get('/appointment/today').then(res => res.data),

  // ========== 管理员专用接口 ==========
  
  // 获取所有预约（管理员权限）
  getAllAppointments: (params?: { 
    status?: string; 
    hospitalId?: string; 
    departmentId?: string; 
    startDate?: string; 
    endDate?: string; 
    page?: number; 
    limit?: number; 
    search?: string 
  }): Promise<AppointmentListResponse> =>
    apiClient.get('/appointment/admin/orders', { params }).then(res => res.data),

  // 更新预约状态（管理员权限）
  updateAppointmentStatus: (appointmentId: string, data: { status: string; remark?: string }): Promise<{ success: boolean; message: string; data: AppointmentOrder }> =>
    apiClient.put(`/appointment/admin/orders/${appointmentId}/status`, data).then(res => res.data),

  // 批量更新预约状态（管理员权限）
  batchUpdateAppointmentStatus: (data: { appointmentIds: string[]; status: string; remark?: string }): Promise<{ success: boolean; message: string; data: { updated: AppointmentOrder[]; notFound: string[] } }> =>
    apiClient.put('/appointment/admin/orders/batch-status', data).then(res => res.data),

  // 获取预约统计数据（管理员权限）
  getAppointmentStats: (params?: { startDate?: string; endDate?: string; hospitalId?: string }): Promise<{
    success: boolean;
    data: {
      overview: {
        total: number;
        pending: number;
        confirmed: number;
        completed: number;
        cancelled: number;
        todayAppointments: number;
        upcomingAppointments: number;
      };
      hospitalStats: Array<{
        hospitalId: string;
        hospitalName: string;
        total: number;
        pending: number;
        confirmed: number;
        completed: number;
        cancelled: number;
      }>;
      dateStats: Array<{
        date: string;
        total: number;
        pending: number;
        confirmed: number;
        completed: number;
        cancelled: number;
      }>;
    };
  }> =>
    apiClient.get('/appointment/admin/stats', { params }).then(res => res.data),

  // 删除预约（管理员权限）
  deleteAppointment: (appointmentId: string): Promise<{ success: boolean; message: string; data: AppointmentOrder }> =>
    apiClient.delete(`/appointment/admin/orders/${appointmentId}`).then(res => res.data),
},

// 患者统计API
patientStats: {
  // 获取患者统计概览
  getOverview: (): Promise<{ success: boolean; data: any }> =>
    apiClient.get('/patient-stats/overview').then(res => res.data),

  // 获取今日门诊患者列表
  getTodayOutpatients: (): Promise<{ success: boolean; data: any[] }> =>
    apiClient.get('/patient-stats/today-outpatients').then(res => res.data),

  // 获取住院患者概览
  getInpatientOverview: (): Promise<{ success: boolean; data: any[] }> =>
    apiClient.get('/patient-stats/inpatient-overview').then(res => res.data),
},
}

// 导出API客户端
export { aiApiClient }

// 服务连接检查
export const checkServiceConnection = async () => {
  const results = {
    aiService: false,
    mainService: false,
    errors: [] as string[]
  }
  
  try {
    await aiApiClient.get('/health', { timeout: 5000 })
    results.aiService = true
  } catch (error: any) {
    results.errors.push(`AI服务连接失败: ${error.message}`)
  }
  
  try {
    await apiClient.get('/health', { timeout: 5000 })
    results.mainService = true
  } catch (error: any) {
    results.errors.push(`主服务连接失败: ${error.message}`)
  }
  
  return results
}

export default apiClient 